#    条件操作                   url
#    $gte       大于等于        id_gte           {id:{$gte:4}}
#    $gt        大于           id_gt            {id:{$gt:4}}
#    $lte       小于等于        id_lte           {id:{$lte:4}}
#    $lt        小于           id_lt             {id:{$lt:4}}
#    $ne        不等于         id_ne             {id:{$ne:4}}
#    $in        在数组中        id_in            {id:{$in:4}}
#    $nin       不在数组中       id_nin           {id:{$nin:4}}
#    /^value/   已value开头    title_startwith           {title:/^4/}}
#    /^value/   已value结尾    title_endwith           {title:/4$/}}
#    /value/    包含          title_like           {title:/^4/}}


#    方法
#    sort           排序                                                  _sort
#    limit          限制数量                                                _limit
#    skip ==_start  从参数index位置开始查询                                  _start  _end
#    count          获取结果数量 返回限制之后的记录数量count(true || 非零)

_ = require('lodash')

mMap =
    'gte': '$gte'
    'gt': '$gt'
    'lte': '$lte'
    'lt': '$lt'
    'ne': '$ne'

mongoChain = (query, col, params)->
    params = params || {}

    _start = parseInt(query._start, 10)
    delete query._start
    _end = parseInt(query._end, 10)
    delete query._end
    _skip = parseInt(query._skip, 10)
    delete query._skip
    _limit = parseInt(query._limit, 10)
    delete query._limit

    _sort = query._sort
    delete query._sort
    _order = parseInt(query._order, 10)
    _order = _order || 1
    delete query._order

    _.each query, (val, q)->
        val = _.trim(val)
        key = q.split('_')[0]
        method = q.split('_')[1]
        return unless method and val
        if method == 'like'
            params[key] = new RegExp("#{val}")
        else if method == 'startwith'
            params[key] = new RegExp("^#{val}")
        else if method == 'endwith'
            params[key] = new RegExp("#{val}$")
        else if method == 'in'
            params[key] = '$in': val.split(',')
        else if mMap.hasOwnProperty(method)
            params[key] = _.set {}, mMap[method], val

    console.log(params)
    r = col.find(params)

    # 排序
    r = r.sort(_.set {}, _sort, _order) if(_sort)

    # 分页
    r = r.skip(_start) if(_start)

    if _end
        r = r.limit(_end)
    else if _limit
        r = r.limit(_start + _limit)

    return r

module.exports = mongoChain
